package com.brand.data.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;

/**
 * @author scl
 * @version 1.0
 * @date 2018年4月11日 下午2:56:41
 * @description API测试接口
 */
@Slf4j
public class AuthUtil {
    private static String AUCODE_FILENAME = "authCode.png";
    private static final String AUTH_URL = "http://yanzhengma.bi.xin.com";

    public static String getAuthCode(byte[] imaByte) {
        return getAuthCode(Base64.encodeBase64String(imaByte));
    }

    public static String getAuth(String prifix, byte[] imaByte) {
        File file = new File("auth/" + prifix + AUCODE_FILENAME);
        File authImage = getAuthImage(file, imaByte);
        try {
            imaByte = IOUtils.toByteArray(new FileInputStream(authImage));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return getAuthCode(Base64.encodeBase64String(imaByte));
    }

    public static String getAuthCode(String base64String) {
        Connection connection = Jsoup.connect(AUTH_URL).ignoreContentType(true).timeout(3000)
                .data("image_data", base64String);
        try {
            connection.post();
            String body = connection.response().body();
            body = JSON.parseObject(body).getString("ocr_result");
            body = body.replaceAll("[^a-zA-Z\\d]", "");
            log.info("获取的验证码是:{}", body);
            return body;
        } catch (IOException e) {
            log.error("获取验证码失败,{}", e.getMessage());
        }
        return null;
    }

    /*public static String getAuthCode(String prifix, byte[] imaByte) {
        File file = new File("auth/" + prifix + AUCODE_FILENAME);
        File authImage = getAuthImage(file, imaByte);
        ITesseract tesseract = new Tesseract();
        String ocrResult = null;
        try {
            tesseract.setDatapath(LoadLibs.extractTessResources("tessdata").getAbsolutePath());
            ocrResult = tesseract.doOCR(authImage);
            ocrResult = ocrResult.replaceAll("[^a-zA-Z\\d]", "");
            System.out.println(ocrResult);
        } catch (Exception e) {
            System.out.println("获取验证码失败,{}" + e);
            log.error("获取验证码失败,{}", e.getMessage());
        }
        return ocrResult;
    }*/

    private static File getAuthImage(File file, byte[] imaByte) {
        writeFile(file, imaByte);
        return binaryImage(file);
    }

    public static void writeFile(File file, byte[] imaByte) {
        FileOutputStream imageOutputStream = null;
        try {
            if (!file.exists()) {
                FileUtils.forceMkdirParent(file);
            }
            imageOutputStream = new FileOutputStream(file);
            imageOutputStream.write(imaByte, 0, imaByte.length);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (imageOutputStream != null)
                try {
                    imageOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }

    public static File binaryImage(File file) {
        try {
            BufferedImage image = ImageIO.read(file);
            int width = image.getWidth();
            int height = image.getHeight();

            BufferedImage imageBinary = new BufferedImage(width - 2, height - 2, 12);
            for (int i = 1; i < width - 1; i++) {
                for (int j = 1; j < height - 1; j++) {
                    int rgb = image.getRGB(i, j);
                    imageBinary.setRGB(i - 1, j - 1, rgb);
                }
            }
            ImageIO.write(imageBinary, "png", file);
            return file;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
